//
//  GLWXManager.m
//  health
//
//  Created by zglee on 2/11/20.
//  Copyright © 2020 zglee. All rights reserved.
//

#import "BabyBlueToothManager.h"
#import "MJTranslateTool.h"

@interface BabyBlueToothManager()


@end


@implementation BabyBlueToothManager

/**
将蓝牙模块进行封装单例
初始化蓝牙设置蓝牙中心设备
*/
+(instancetype)shared
{
    static BabyBlueToothManager *babyBluetooth;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        babyBluetooth = [[BabyBlueToothManager alloc] init];
        // 初始化 baby 蓝牙库
        babyBluetooth.baby = [BabyBluetooth shareBabyBluetooth];
        // 设置蓝牙代理
        [babyBluetooth babyDelegate];
    });
    return babyBluetooth;
}
//设置蓝牙委托
-(void)babyDelegate{

    /**
    搜索设备获取中心设备，
    外设
    外设advertisementData数据（广告数据），通常情况下mac地址会存储在这里
    RSSI为信号强度
    */
    __weak __typeof(self)weakSelf = self;
    //设置扫描到设备的委托
    
    [self.baby setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
        NSLog(@"搜索到了设备====设备名称====%@",peripheral.name);
        
        NSMutableArray *perpherals = weakSelf.peripherals;
        if (perpherals.count == 0) {
            [perpherals addObject:peripheral];
        } else {
            BOOL isExist = NO;
            for (int i = 0; i < perpherals.count; i++) {
                CBPeripheral *per = [perpherals objectAtIndex:i];
                if ([per.identifier.UUIDString isEqualToString:peripheral.identifier.UUIDString]) {
                    isExist = YES;
                    [perpherals replaceObjectAtIndex:i withObject:peripheral];
                }
            }
            if (!isExist) {
                [perpherals addObject:peripheral];
            }
        }
        weakSelf.peripherals = perpherals;
        
        NSLog(@"搜索到了设备====设备名称个数====%ld",perpherals.count);
        
    }];
    
    /**
    获取外设后，对外设进行过滤，筛选符合规则的蓝牙设备
    */
    [self.baby setFilterOnDiscoverPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {

        //设置查找规则是名称大于1
        if (peripheralName.length >0 && [peripheralName containsString:mBluetoothNameLBM]) {
            return YES;
        }
        return NO;
    }];
    
    // 蓝牙连接状态
    [self.baby setBlockOnCentralManagerDidUpdateState:^(CBCentralManager *central) {

        NSLog(@"蓝牙连接状态==========%ld",central.state);
        weakSelf.central = central;
        
    }];
    #pragma mark ************** 连接成功
    //.......
    /**************设备连接状态回调****************/
    // 设备连接成功
        [_baby setBlockOnConnected:^(CBCentralManager *central, CBPeripheral *peripheral) {
            
            
            weakSelf.repeatflag = false;
//            weakSelf.repeatTypeflag = false;
            //记住常用设备
            [MJUIUserDeFault setObject:peripheral.identifier.UUIDString forKey:Common_equipment_uuid];

            NSLog(@"设备：%@--连接成功",peripheral.name);
//            [RoyHud showToast:@"设备连接成功"];
            
            weakSelf.peripheral = peripheral;
            [weakSelf stopScan];

        }];

    //设置设备连接失败的委托
        [_baby setBlockOnFailToConnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
            NSLog(@"设备：%@--连接失败",peripheral.name);
//            [RoyHud showToast:@"设备连接失败"];
            weakSelf.peripheral = nil;
            weakSelf.peripherals = [NSMutableArray array];
        }];
    

    //设置设备断开连接的委托
        [_baby setBlockOnDisconnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
            weakSelf.repeatTypeflag = false;
            weakSelf.repeatflag = false;
            // 这里可以处理重新连接
            NSLog(@"设备：%@--断开连接",peripheral.name);
//            [RoyHud showToast:@"断开连接"];
            weakSelf.peripheral = nil;
            weakSelf.peripherals = [NSMutableArray array];

            //非4和一
            if(!weakSelf.isDisease4){
                //记住上次的试纸类型(app主动断开蓝牙的，则不需要清除)
                if(!weakSelf.selfDisconnection){
                    [MJUIUserDeFault setObject:nil forKey:LastDetectionItemType];
                }else{
                    weakSelf.selfDisconnection = false;
                }
            }
        }];
    
    /**************连接成功后发现设备服务（service）****************/
    // 发现设备服务
     [_baby setBlockOnDiscoverServices:^(CBPeripheral *peripheral, NSError *error) {
            for (CBService *s in peripheral.services) {
                //每个service
            }
         
         //设置时间，得等到滴血之后 [-111, 8, 83, 23, 3, 29, 10, 18, 35, -47, 0]
         MJUIAfter_GCD(8, ^{
//           [weakSelf write:[MJManager getTimeWriteData]];
         });
        
        }];
    //设置发现设service的Characteristics的委托
      [_baby setBlockOnDiscoverCharacteristics:^(CBPeripheral *peripheral, CBService *service, NSError *error) {
//          NSLog(@"=========service name====%@",service.UUID.UUIDString); //打印Device Information/Battery/FFE5 等
          
          BOOL isExistServiceUUID = ([service.UUID.UUIDString isEqualToString:writeServerUUIDString] || [service.UUID.UUIDString isEqualToString:readServerUUIDString] || [service.UUID.UUIDString isEqualToString:newBLEServerUUIDString]);
          
            if(isExistServiceUUID){
                
                [service.characteristics enumerateObjectsUsingBlock:^(CBCharacteristic * _Nonnull characteristic, NSUInteger idx, BOOL * _Nonnull stop) {
                    
//                    NSLog(@"=========characteristic name====%@",characteristic.UUID.UUIDString); //打印Device Information/Battery/FFE5 等

                    // 通过枚举获取服务特征
                    if([characteristic.UUID.UUIDString isEqualToString:writeUUIDString] || [characteristic.UUID.UUIDString isEqualToString:newBLEWriteUUIDString]){
                        NSLog(@"writeUUIDString=====UUIDString=========%@=========properties=========%ld",characteristic.UUID.UUIDString,characteristic.properties);
                        
                        if(characteristic.properties & CBCharacteristicPropertyWrite){
//                            NSLog(@"writeUUIDString=====CBCharacteristicPropertyWrite");
                            weakSelf.writeCharacteristic = characteristic;
                        }
                        
                        
                    }else if([characteristic.UUID.UUIDString isEqualToString:readUUIDString] || [characteristic.UUID.UUIDString isEqualToString:newBLEReadUUIDString]){
                        NSLog(@"readUUIDString=====UUIDString=========%@=========properties=========%ld",characteristic.UUID.UUIDString,characteristic.properties);

//                        //读取
//                        if (characteristic.properties & CBCharacteristicPropertyRead) {
//                            [peripheral readValueForCharacteristic:characteristic];
//                        }
//                        //订阅
//                        if ((characteristic.properties & CBCharacteristicPropertyNotify) ||
//                            (characteristic.properties & CBCharacteristicPropertyIndicate))
//                        {
//                            [peripheral setNotifyValue:YES
//                                          forCharacteristic:characteristic];
//                        }

                        
                        //接收数据
                        #pragma mark ************** 读取回调
                        [weakSelf.baby notify:weakSelf.peripheral characteristic:characteristic block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
                            
                            if(error){
                                
                            }else{
                                [weakSelf processingData:characteristics];

                            }
                            //A138A1 00 E6 1307120E2232A302F2000000000000
//                            NSLog(@"收到的指令数据characteristic=========UUID=======%@==========UUIDString=========%@=====properties==== %lu ", characteristics.UUID , characteristics.UUID.UUIDString, (unsigned long)characteristics.properties);
//                            [weakSelf processingData:characteristics];
                            
                        }];
                        
                    }
                    
                    
                    
                }];
                
            }
            
            
        }];
     
     //设置发现characteristics的descriptors的委托  发现特征回调
        [_baby setBlockOnDiscoverDescriptorsForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristic, NSError *error) {
            

        }];
     #pragma mark ************** 写入回调
    [_baby setBlockOnDidWriteValueForCharacteristic:^(CBCharacteristic *characteristic, NSError *error) {
        if(error){
            NSLog(@"write error ====== %@", error);
        }else{
            NSLog(@"write value success(写入成功) : %@", characteristic);
//            [weakSelf.peripheral readValueForCharacteristic:characteristic];

        }

    }];
    
    [_baby setBlockOnDidUpdateNotificationStateForCharacteristic:^(CBCharacteristic *characteristic, NSError *error) {
        // 收到的指令数据  FFE4
       
    }];
    
    /**************读取设备服务-特征的数据****************/
    [_baby setBlockOnReadValueForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {



    }];
    
    /**************设置读取Descriptor的委托****************/
       [_baby setBlockOnReadValueForDescriptors:^(CBPeripheral *peripheral, CBDescriptor *descriptor, NSError *error) {
           

       }];
    
    
}

//解析数据
- (void)processingData:(CBCharacteristic *)characteristics{
    
    NSString *valueHex = [MJTranslateTool hexStringFromData:characteristics.value];
    valueHex = [valueHex uppercaseString];
    NSLog(@"valueHex原数据=======================%@",valueHex);

    NSString * deviceType = [valueHex substringToIndex:2];
    if([deviceType isEqualToString:deviceTypeL01] || [deviceType isEqualToString:deviceTypeL02] || [deviceType isEqualToString:deviceTypeL03] || [deviceType isEqualToString:deviceTypeL04]){
        
        self.deviceType = deviceType;
        
        if ([valueHex hasPrefix:[deviceType stringByAppendingString:@"38A1"]]) {
            
            NSLog(@"当前浓度数据=======================%@",valueHex);
            if (valueHex.length >= 28) {
                valueHex = [valueHex substringToIndex:28];// 截取前十四位
            }else{
                return;
            }
            if (!self.repeatflag) {
                [self processingUricAcidData:valueHex deviceType:deviceType];
                self.repeatflag = true;
            }
            // 发送当前浓度数据
            [self write:[MJTranslateTool convertHexStrToData:[deviceType stringByAppendingString:@"025153"]]];
           
        }else if([valueHex hasPrefix:[deviceType stringByAppendingString:@"38A2"]]){
            
            NSLog(@"历史浓度数据=======================%@",valueHex);
            [self write:[MJTranslateTool convertHexStrToData:[deviceType stringByAppendingString:@"025154"]]];
            
        }else if([valueHex hasPrefix:@"9102A3A5"]){
            
            NSLog(@"收到数据9102A3A5======%@",valueHex);//A138A2016C16070F0E0F12A6024A
            
        }else if([valueHex hasPrefix:[deviceType stringByAppendingString:@"03A4"]]){
            
            NSLog(@"发送试纸类别=======================%@",valueHex);//78 03A4 A44B
            //11
            if (!self.repeatTypeflag) {
                [self processingDetectionType:valueHex];
            }
            
        }else if([valueHex hasPrefix:[deviceType stringByAppendingString:@"03A7"]]){
            
            NSLog(@"发送仪器ERR码=======================%@",valueHex);//6803A702AC
            [self processingDetectionErrorType:valueHex];
        }
    }
}

/*
 1. Er2：试纸过期或已使用

 2. Er3：采样过快

 3. Er4：试纸不适用

 4. Er5：采样量不足

 5. Er8：重新插入试纸
 */

/// 仪器错误码
- (void)processingDetectionErrorType:(NSString *)valueHex{
    NSString *typeString = [valueHex substringWithRange:NSMakeRange(6, 2)];//7803A702AC
    if (self.delegate && [self.delegate respondsToSelector:@selector(blueToothManagerErrorType:)]){
        [self.delegate blueToothManagerErrorType:typeString];
    }
}

/// 检测类型
- (void)processingDetectionType:(NSString *)valueHex{
    NSString *typeString = [valueHex substringWithRange:NSMakeRange(6, 2)];
    
    if(!self.isDisease4){
        //记住上次的试纸类型
        [MJUIUserDeFault setObject:typeString forKey:LastDetectionItemType];
    }
    
    DetectionPaperType detectionPaperType = DetectionPaperTypeUA;
    DetectionItemType detectionItemType = DetectionItemTypeMultiple;
    if([typeString isEqualToString:bloodUricAcidType]){
        detectionPaperType = DetectionPaperTypeUA;
        detectionItemType = DetectionItemTypeGout;
    }
    if([typeString isEqualToString:urineUricAcidType]){
        detectionPaperType = DetectionPaperTypeUUA;
        detectionItemType = DetectionItemTypeGout;

    }
    if([typeString isEqualToString:bloodSugarType]){
        detectionPaperType = DetectionPaperTypeGlu;
        detectionItemType = DetectionItemTypeGlu;

    }
    if([typeString isEqualToString:totalCholesterolType]){
        detectionPaperType = DetectionPaperTypeTC;
        detectionItemType = DetectionItemTypeTC;

    }
    if([typeString isEqualToString:hemoglobinType]){
        detectionPaperType = DetectionPaperTypeHB;
        detectionItemType = DetectionItemTypeHB;

    }
   
    if (self.delegate && [self.delegate respondsToSelector:@selector(blueToothManagerDetectionPaperType:detectionItemType:)]){
        [self.delegate blueToothManagerDetectionPaperType:detectionPaperType detectionItemType:detectionItemType];
    }
}

- (void)processingUricAcidData:(NSString *)valueHex deviceType:(NSString *)deviceType{
    //A138A1 01 3D 13 0A1C083529 A6 025E   、‘’‘A138A100E7150213160812A302BF  A138A100E8150213160D21A302D4 A138A10144150213161200A60218 A138A20144150213161200A60219000000000000
    // 浓度
    // 浓度1
    NSString *consistence1 = [valueHex substringWithRange:NSMakeRange(6, 2)];
    // 浓度2
    NSString *consistence2 = [valueHex substringWithRange:NSMakeRange(8, 2)];
    // 浓度1+浓度2
    NSString *totalCon = [NSString stringWithFormat:@"%@%@",consistence1,consistence2];
    // 十六进制转换为十进制
    NSInteger valueInt = [MJTranslateTool getDecimalByHex:totalCon];
    NSLog(@"consistence1======%@======consistence2======%@==========valueInt=======%ld",consistence1,consistence2,valueInt);

    // 截取测试数据类型 a3：血尿酸   a6:尿尿酸
    NSString * valueType = [valueHex substringWithRange:NSMakeRange(22, 2)];

    if ([valueType isEqualToString:bloodUricAcidType]) {
        // 血尿酸水平 a3
        
        NSString *unit = unitμmolL;
        NSString *valueString = [NSString stringWithFormat:@"%ld",valueInt];
        if([deviceType isEqualToString:deviceTypeL01]){
            valueString = [NSString stringWithFormat:@"%.2f",valueInt/100.0];
            unit = unitmgdL;
        }
        
        NSMutableDictionary *valueDic = [[NSMutableDictionary alloc] init];
        [valueDic setValue:valueString forKey:@"value"];
        [valueDic setValue:bloodUricAcidType forKey:@"type"];
        [valueDic setValue:unit forKey:@"unit"];
        [valueDic setValue:bloodUricAcidAbbr forKey:@"abbr"];

        self.detectionValueDic = valueDic;
        
    } else if ([valueType isEqualToString:urineUricAcidType]) {
        // 肾尿酸水平 a6
        CGFloat value = valueInt/100.0;//[[NSString stringWithFormat:@"%.2f",] floatValue];
        if ([consistence1 isEqualToString:@"FF"]) {
            value = ([MJTranslateTool getDecimalByHex:consistence2]-256)/100.0;
        }
        
        NSMutableDictionary *valueDic = [[NSMutableDictionary alloc] init];
        [valueDic setValue:[NSString stringWithFormat:@"%.2f",value] forKey:@"value"];
        [valueDic setValue:urineUricAcidType forKey:@"type"];

        self.detectionValueDic = valueDic;
    
    }else if ([valueType isEqualToString:bloodSugarType]) {
        // 血糖 A2
        NSString *unit = unitmmolL;
        NSString *valueString = [NSString stringWithFormat:@"%.2f",valueInt/100.0];
        if([deviceType isEqualToString:deviceTypeL01]){
            valueString = [NSString stringWithFormat:@"%ld",valueInt];
            unit = unitmgdL;
        }
        
        NSMutableDictionary *valueDic = [[NSMutableDictionary alloc] init];
        [valueDic setValue:valueString forKey:@"value"];
        [valueDic setValue:bloodSugarType forKey:@"type"];
        [valueDic setValue:unit forKey:@"unit"];
        [valueDic setValue:bloodSugarAbbr forKey:@"abbr"];

        self.detectionValueDic = valueDic;
    
    }else if ([valueType isEqualToString:totalCholesterolType]) {
        
        // 胆固醇 A4
        NSString *unit = unitmmolL;
        NSString *valueString = [NSString stringWithFormat:@"%.2f",valueInt/100.0];
        if([deviceType isEqualToString:deviceTypeL01]){
            valueString = [NSString stringWithFormat:@"%ld",valueInt];
            unit = unitmgdL;
        }
        
        NSMutableDictionary *valueDic = [[NSMutableDictionary alloc] init];
        [valueDic setValue:valueString forKey:@"value"];
        [valueDic setValue:totalCholesterolType forKey:@"type"];
        [valueDic setValue:unit forKey:@"unit"];
        [valueDic setValue:totalCholesterolAbbr forKey:@"abbr"];

        self.detectionValueDic = valueDic;
    }else if ([valueType isEqualToString:hemoglobinType]) {
        
        // 血红蛋白 A5
        NSString *unit = unitgdL;
//        NSString *valueString = [NSString stringWithFormat:@"%ld",valueInt];
        NSString *valueString = valueString = [NSString stringWithFormat:@"%.2f",valueInt/100.0];
        if([deviceType isEqualToString:deviceTypeL02]){
            unit = unitmmolL;
        }else if([deviceType isEqualToString:deviceTypeL04]){
            valueString = [NSString stringWithFormat:@"%ld",valueInt];
            unit = unitgL;
        }
        
        NSMutableDictionary *valueDic = [[NSMutableDictionary alloc] init];
        [valueDic setValue:valueString forKey:@"value"];
        [valueDic setValue:hemoglobinType forKey:@"type"];
        [valueDic setValue:unit forKey:@"unit"];
        [valueDic setValue:hemoglobinAbbr forKey:@"abbr"];

        self.detectionValueDic = valueDic;
    }
    
}






///发送数据
#pragma mark ************** 发送数据
- (void)write:(NSData *)msgData {
    if (self.writeCharacteristic == nil) {
        NSLog(@"【HKBabyBluetooth】->数据发送失败");
        return;
    }
//    NSData* msgData = [MJTranslateTool convertHexStrToData:msg];
//    NSLog(@"msgData=====================%@",msgData);

    
    //若最后一个参数是CBCharacteristicWriteWithResponse
    //则会进入setBlockOnDidWriteValueForCharacteristic委托
    if (self.writeCharacteristic.properties & CBCharacteristicPropertyWrite) {
        [self.peripheral writeValue:msgData
                         forCharacteristic:self.writeCharacteristic
                                      type:CBCharacteristicWriteWithoutResponse];
    }else{
        NSLog(@"该字段不可写！");
    }
    
    
}



/**
 连接蓝牙
 */
- (void)connetBlueToothWithCBPeripheral:(CBPeripheral *)peripheral {
    
    // 连接外设.发现服务.发现特征.读取特征数据.发现特征数据(键值对).读取特征描述.开始连接
    self.baby.having(peripheral).connectToPeripherals().discoverServices().discoverCharacteristics().readValueForCharacteristic().discoverDescriptorsForCharacteristic().readValueForDescriptors().begin();
    // 取消搜索蓝牙
    [self.baby cancelScan];

}
//断开连接
- (void)cancelPeripheralConnection:(CBPeripheral *)peripheral {
    [self.baby cancelPeripheralConnection:peripheral];
          
//          [self cancelAllPeripheralsConnection];
}
//断开所有连接
- (void)cancelAllPeripheralsConnection {
    [self.baby cancelAllPeripheralsConnection];
}

/**
 *  开始扫描
 */
-(void)startScan{
    //已连接设备
    if(self.peripheral){
        return;
    }
    
    //立刻执行
    if(!_timerReloadList){
        NSLog(@"立刻执行=====11");
        [self.timerReloadList setFireDate:[NSDate distantPast]];
    }
}
-(void)stopScan{
    //结束定时器
    [self.timerReloadList invalidate];//释放
    self.timerReloadList = nil;
    [self.baby cancelScan];
   
}
- (void)cancelPeripheral{
    if(self.peripheral){
        
        //主动断开
        self.selfDisconnection = true;
        [self cancelPeripheralConnection:self.peripheral];
        
    }
}

- (NSMutableArray *)peripherals {
    if (_peripherals == nil) {
        _peripherals = [NSMutableArray array];
    }
    return _peripherals;
}

- (NSTimer *)timerReloadList
{
    if (!_timerReloadList) {
        _timerReloadList = [NSTimer scheduledTimerWithTimeInterval:3
                                                            target:self
                                                          selector:@selector(searchDeviceList)
                                                          userInfo:nil
                                                           repeats:YES];
    }
    return _timerReloadList;
}
- (void)searchDeviceList{
    
    if(!UserManager.shared.userModel){
        return;
    }
    NSLog(@"begin=====开始扫描");
    
    self.baby.scanForPeripherals().begin();
    
      if(!self.peripheral){
          if (self.delegate && [self.delegate respondsToSelector:@selector(beginSearchDeviceList)]){
              [self.delegate beginSearchDeviceList];
          }
      }
    
//    self.peripherals = [NSMutableArray array];
//
    
          

    
}

@end
